import React, { useState, useEffect }  from 'react'
import { useParams } from 'react-router-dom';
import { Card, Divider, Tag } from 'antd';
import { CalendarOutlined } from '@ant-design/icons';
import { findBlogById } from '@/api/blog';
import css from './index.module.less';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {vscDarkPlus} from 'react-syntax-highlighter/dist/esm/styles/prism'

export default function Index() {
	const params = useParams();
	const [data, setData] = useState(null);
	useEffect(() => {
		findBlogById(params.id).then((res) => {
			if (res.code === 200) {
				setData(res.data);
				console.log(res.data)
			}
		})
	}, [])
	const colors = ["magenta", "red", "volcano", "orange", "green", "yellow", "blue", "gold"];
	return (
		<div className={css.card}>
			{data === null? <></> :
				<Card
				hoverable
				className={css.card}
			>
				<div className={css.content}>
					<h1 className={css.title}>{data.blog.title}</h1>
					<Divider style={{margin: 0}} />
					<div className={css.category}>
						<CalendarOutlined /> <span>更新时间: {data.blog.created}</span>
						<Divider type="vertical" />
						{data.categories.map((category, index) => {
							return (
								<Tag color={colors[Math.round(Math.random() * colors.length)]} key={index}>
								<span>{category.title} </span>
							</Tag>)
						})}
					</div>
					<ReactMarkdown
						children={data.blog.content}
						components={{
							img(props) {
								return <img {...props} style={{ maxWidth: '100%' }}/>
							},
							code({node, inline, className, children, ...props}) {
								const match = /language-(\w+)/.exec(className || '')
								return !inline && match ? (
									<SyntaxHighlighter
										children={String(children).replace(/\n$/, '')}
										style={vscDarkPlus}
										language={match[1]}
										PreTag="div"
										{...props}
									/>
								) : (
									<code className={className} {...props}>
										{children}
									</code>
								)
							}
						}}
						remarkPlugins={[remarkGfm]}
						rehypePlugins={[rehypeRaw]}
					/>
					<Card style={{padding: 0}} className={css.copyright}>
						<h4>Author: <span>{data.author}</span></h4>
						<h4>Copyright Notice: <span>此文章版权归作者所有，如有转载，请註明来自原作者。</span></h4>
					</Card>
					<div className={css.category}>
						{data.categories.map((category, index) => {
							return (
								<Tag color={colors[Math.round(Math.random() * colors.length)]} key={index}>
									<span>{category.title} </span>
								</Tag>)
						})}
					</div>
				</div>
			</Card>}
		</div>
	)
}
